package com.lc.fbtp.draftmsg.core.schema;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lc.fbtp.draftmsg.api.paper.DraftInfo;
import com.lc.fbtp.draftmsg.api.paper.MsgHeader;
import com.lc.fbtp.draftmsg.core.utils.SHA256;

public class ValidateDraftInfo {
	
	private static final Logger logger = LoggerFactory.getLogger(ValidateDraftInfo.class);

	/**
	 * 报文Document格式验证
	 * @param draftInfo
	 * @return
	 */
	public static boolean validateMainBodyXml(DraftInfo draftInfo){
		MsgHeader msgHeader = draftInfo.getMsgHeader();
		String mesgType = msgHeader.getMesgType();
		Validator validator = ValidatorCache.getValidator(mesgType);
		if(validator == null){
			logger.error("未找到Document格式验证器，不存在{}类型的schema文件！", mesgType);
			throw new NullPointerException();
		}
		InputStream input = new ByteArrayInputStream(draftInfo.getMsgBodyStr().getBytes());
		try {
			validator.validate(new StreamSource(input));
			return true;
		} catch (Exception e) {
			logger.error("XML格式非法,非法报文：{}", draftInfo.getMsgBodyStr());
			logger.error("Document内容验证格式出错", e);
			return false;
		}
	}
	/**
	 * 校验和验证
	 * @param draftInfo
	 * @return
	 */
	public static boolean validateBodyChksum(DraftInfo draftInfo) {
		String encryStr = SHA256.encry(draftInfo.getMsgBodyStr());
		return encryStr.equals(draftInfo.getMsgHeader().getBodyChksum());
	}
}
